Page({
  data: {
    mainImage: '', // 第一张图（主图）
    qrImage: '', // 第二张图（二维码）
    mergedImage: '',
    canvasWidth: 0,
    canvasHeight: 0
  },

  onLoad(options) {
    // 从上个页面带来的图片 URL
    const mainImage = decodeURIComponent(options.mainImage);
    const qrImage = decodeURIComponent(options.qrImage);
    this.setData({
      mainImage,
      qrImage
    });
  },

  // 点击主图触发上传
  uploadMainImage() {
    const that = this;
    wx.chooseImage({
      count: 1, // 只选一张
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // res.tempFilePaths 是选择的本地文件路径数组
        that.setData({
          mainImage: res.tempFilePaths[0]
        });
      },
      fail(err) {
        console.error('选择图片失败:', err);
      }
    });
  },


  // merge-image.js
  handleMerge() {
    // wx.showLoading({ title: '正在合并...' })

    const query = wx.createSelectorQuery()
    query.select('#mergeCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')

        const dpr = wx.getWindowInfo().pixelRatio
        const width = 300
        const height = 300

        canvas.width = width * dpr
        canvas.height = height * dpr
        ctx.scale(dpr, dpr)

        // 创建主图
        const mainImg = canvas.createImage()
        mainImg.src = this.data.mainImage

        mainImg.onload = () => {
          // ctx.drawImage(mainImg, 0, 0, width, height)
          // 获取图像的原始尺寸
          const imgWidth = mainImg.width;
          const imgHeight = mainImg.height;

          // 判断图像是否已经是1:1的比例
          if (imgWidth === imgHeight) {
            // 如果是1:1的比例，直接绘制图像
            ctx.drawImage(mainImg, 0, 0, width, height);
          } else {
            // 如果不是1:1的比例，计算缩放比例和截取区域
            let scale;
            let srcWidth, srcHeight, srcX, srcY;

            if (imgWidth > imgHeight) {
              // 图像宽度大于高度
              scale = imgHeight / imgWidth;
              srcWidth = imgWidth * scale;
              srcHeight = imgHeight;
              srcX = (imgWidth - srcWidth) / 2;
              srcY = 0;
            } else {
              // 图像高度大于宽度
              scale = imgWidth / imgHeight;
              srcWidth = imgWidth;
              srcHeight = imgHeight * scale;
              srcX = 0;
              srcY = (imgHeight - srcHeight) / 2;
            }

            // 绘制图像
            ctx.drawImage(mainImg, srcX, srcY, srcWidth, srcHeight, 0, 0, width, height);
          }

          // 创建二维码图
          const qrImg = canvas.createImage()
          qrImg.src = this.data.qrImage

          qrImg.onload = () => {
            const qrSize = 80
            // 左上角
            ctx.drawImage(qrImg, 0, 0, qrSize, qrSize);

            // 右上角
            ctx.drawImage(qrImg, width - qrSize, 0, qrSize, qrSize);

            // 左下角
            ctx.drawImage(qrImg, 0, height - qrSize, qrSize, qrSize);

            // 右下角
            ctx.drawImage(qrImg, width - qrSize, height - qrSize, qrSize, qrSize);



            // ✅ 用 wx.canvasToTempFilePath，而不是 canvas.toTempFilePath
            wx.canvasToTempFilePath({
              canvas, // 注意是 canvas 对象，不是 canvasId！
              x: 0,
              y: 0,
              width: width,
              height: height,
              destWidth: width * dpr,
              destHeight: height * dpr,
              success: (res) => {
                this.setData({
                  mergedImage: res.tempFilePath
                })
                // wx.hideLoading()
              },
              fail: (err) => {
                console.error("合成失败", err)
                // wx.hideLoading()
              }
            }, this)
          }
        }
      })
  }
})